package com.nhncorp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPSClient;



public class FtpUploader extends Thread{
	
	private String serverIp;
	private String uploadId;
	private String[] filePathArray;
	
	
	public FtpUploader(String uploadId, String serverIp, String[] filePathArray){
		this.uploadId = uploadId;
		this.serverIp = serverIp;
		this.filePathArray = filePathArray;
	}
	
	public void run(){
		System.out.println("== method start : {} : {}" + this.getId() + getNowTime());

		FileInputStream fis = null;
		File uploadFile = null;
		
		FTPSClient ftps = new FTPSClient(true);
		
		for(int i = 0 ; i < filePathArray.length ; i++){
			uploadFile = new File(filePathArray[i]);
			
			try{
				ftps.setControlEncoding("UTF-8");
				InetAddress inet = InetAddress.getByName("125.209.205.39");
				
				ftps.connect(inet, 10024);
//				System.out.println("==== connected : {} : {}" + this.getId() + getNowTime());
//				
//				ftps.login(uploadId, "1111");
//				System.out.println("==== logined : {} : {}" + this.getId() + getNowTime());
//				
//				ftps.setConnectTimeout(1000);
//				ftps.enterLocalPassiveMode();
//				
//				ftps.setFileType(FTP.BINARY_FILE_TYPE);
//				try{
//					fis = new FileInputStream(uploadFile);
//					ftps.storeFile(uploadFile.getName(), fis);
//				}
//				catch(IOException ex){
//					System.out.println("==== file input IO Exception : {} : {}" + i + " || " + this.getId() + ex.getMessage());
//					ex.printStackTrace();
//				}
//				finally{
//					if (fis != null){
//						try{
//							fis.close();        // Stream 닫기
//						}catch(IOException ex){
//							System.out.println("==== file close IO Exception : {} : {}" + i + " || " + this.getId() + ex.getMessage());
//							ex.printStackTrace();
//						}
//					}
//				}
//				ftps.logout();
//				System.out.println("==== logout : {} : {}" + this.getId() + getNowTime());
			}
			catch(IOException e){
				System.out.println("==== IO : {} : {}" + i + " || " + this.getId() + e.getMessage());
				e.printStackTrace();
			}
			finally{
				if (ftps != null && ftps.isConnected()){
					try{
						ftps.disconnect();
						System.out.println("==== disconnect : {} : {}" + this.getId() + i);
					}
					catch (IOException e){
						System.out.println("==== disconnected IO Exception : {} : {}" + i + " || " + this.getId() + e.getMessage());
						e.printStackTrace();
					}
				}
			}
		}
		System.out.println("==== method end : {} : {}" + this.getId() + getNowTime());
	}
	private String getNowTime(){
		GregorianCalendar gc = new GregorianCalendar();
        SimpleDateFormat sf = new SimpleDateFormat("MM/dd HH:mm:ss");
        return sf.format(gc.getTime());
	}
}